package com.project.nimsen.web.sys;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dto.ArchivesDto;
import com.project.nimsen.dto.ColfileDto;
import com.project.nimsen.dto.ColumnDto;
import com.project.nimsen.entity.Coltype;
import com.project.nimsen.entity.User;
import com.project.nimsen.service.IArchivesService;
import com.project.nimsen.service.IColfileService;
import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.service.ISiteService;
import com.project.nimsen.util.NimsenUtil;
import com.project.nimsen.util.WebUtil;
import com.project.jdbc.utils.DateUtils;
import com.project.jdbc.web.BaseMVCAction;
/**
 * 栏目Control
 * */
@Controller
@RequestMapping(value ="/sys/column")
public class ColumnControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IColtypeService coltypeService;
	@Resource
	IArchivesService archivesService;
	@Resource
	ISiteService siteService;
	@Resource
	IColfileService colfileService;
	/**
	 * 跳转面面
	 * */
	@RequestMapping(value ="/list")
	public String list(){
		return "/WEB-INF/sys/column/list";
	}
	/**
	 * 添加时的验证信息
	 * 在同一级别下的验证
	 * */
	@RequestMapping(value ="/validate")
	@ResponseBody
	public Map<String, Object> validate(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			ColumnDto dto = new ColumnDto();
			addDtoSiteId(dto);
			dto.setPnumber(getParameter("pnumber"));
			dto.setValifield("colname");
			dto.setValivalue(getParameter("colname"));
			dto.setId(getParameter("id"));
			StringBuffer sbfMessage = new StringBuffer();
			boolean validate = true;
			Map<String, Object> colnameMap = coltypeService.findVilidate(dto);
			if(colnameMap!=null){
				validate = false;
				sbfMessage.append(" 栏目名称");
			}
			
			dto.setValifield("sort");
			dto.setValivalue(getParameter("sort"));
			Map<String, Object> sortMap = coltypeService.findVilidate(dto);
			if(sortMap!=null){
				validate = false;
				sbfMessage.append(" 排序值");
			}
			
			dto.setValifield("vurl");
			dto.setValivalue(getParameter("vurl"));
			Map<String, Object> vurlMap = coltypeService.findVilidate(dto);
			if(vurlMap!=null){
				validate = false;
				sbfMessage.append(" 访问路径");
			}
			
			if(!validate)
				map.put("message", "在同一级栏目下有"+sbfMessage.toString()+"信息相同!");
			else
				map.put("message", "");
			map.put("success", validate);
		} catch(Exception e){
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 添加一个栏目信息
	 * */
	@RequestMapping(value ="/add")
	public void add(HttpServletRequest request,HttpServletResponse response){
		User use = webUtil.getCurrUser();
		try {
			String id = getParameter("id");
			Coltype col = null;
			String pnumber = getParameter("pnumber");
			if(StringUtils.isBlank(id)){
				col = new Coltype();
				col.setCreateTime(new Date());
				col.setCreateUser(use.getId());
				col.setActive(0);
				col.setPnumber(pnumber);
				//站点编号
				Map<String, Object> site = siteService.findByManagerId(use.getId());
				String siteid = site.get("id").toString();
				col.setSiteid(siteid);
				//得到当前全录人管理的站点信息
				ColumnDto dto = new ColumnDto();
				dto.setSiteid(siteid);
				dto.setPnumber(pnumber);
				
				col.setNumber(coltypeService.findNextNum(dto));
			}else{
				col = coltypeService.findEntityById(id);
				pnumber = col.getPnumber();
			}
			//属性设置
			col.setColname(getParameter("colname"));
			col.setArchivesmodel(getParameter("archivesmodel"));
			col.setListmodel(getParameter("listmodel"));
			col.setShowstatus(getParameter("showstatus"));
			col.setSort(getIntegerParameter("sort"));
			col.setListmodel(getParameter("listmodel"));
			col.setArchivesmodel(getParameter("archivesmodel"));
			col.setPhonelistmodel(getParameter("phonelistmodel"));
			col.setPhonearchmodel(getParameter("phonearchmodel"));
			col.setPadlistmodel(getParameter("padlistmodel"));
			col.setPadarchmodel(getParameter("padarchmodel"));
			//处理vurl
			String vurl = getParameter("vurl");
			if(StringUtils.isNotBlank(pnumber)){
				Coltype pcol = coltypeService.findEntityByNumer(pnumber, 
					addDtoSiteId(new ColumnDto()));
				col.setVurl(pcol.getVurl()+"/"+vurl);
			}else
				col.setVurl("/"+vurl);
			//保存一个栏目信息
			ColumnDto dto = new ColumnDto();
			dto.setColtype(col);
			dto.setCurruseid(use.getId());
			//封面图片
			dto.setMicroimgid(getParameter("microimgid"));
			coltypeService.save(dto);
			response.getWriter().println(true);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}
	/**
	 * 向前台返回一个实体
	 * */
	@RequestMapping(value = "/bean")
	@ResponseBody
	public Map<String, Object> bean(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		ColumnDto dto = new ColumnDto();
		dto.setId(getParameter("id"));
		try {
			addDtoSiteId(dto);
			Map<String, Object> entity = coltypeService.findEntity(dto);
			if(entity==null){
				map.put("success", false);
				map.put("message", " 找不到要操作的栏目！");
				return map;
			}
			Object vurlObj = entity.get("vurl");
			if(vurlObj!=null){
				String vurl = vurlObj.toString();
				entity.put("vurl", vurl.substring(vurl.lastIndexOf("/")+1));
			}
			ColfileDto cfDto = new ColfileDto();
			cfDto.setColtypeid(NimsenUtil.obj2String(entity.get("id")));
			cfDto.setRelatiovalue(NimsenConstant.FILE_RELATION_MICROIMG);
			List<Map<String, Object>> imgs = colfileService.findFileInfoByDto(cfDto);
			if(CollectionUtils.isEmpty(imgs)){
//				entity.put("imgid", "");
//				entity.put("imgsrc", "");
				map.put("success", true);
				map.put("bean", entity);
				return map;
			}
			//处理缩略图信息
			for(Map<String, Object> img : imgs){
				entity.put("imgid", img.get("id"));
				entity.put("imgsrc", img.get("filename"));
			}
			map.put("success", true);
			map.put("bean", entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			map.put("success", false);
		}
		return map;
	}
	/**
	 * 删除一个栏目
	 * */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		ColumnDto dto = new ColumnDto();
		String id = getParameter("id");
		dto.setId(id);
		try {
			addDtoSiteId(dto);
			//查询是否还有子栏目
			List<Map<String, Object>> childs = coltypeService.findChild(dto);
			if(!CollectionUtils.isEmpty(childs)){
				map.put("success", false);
				map.put("message", "此栏目下有子栏目，请先删除子栏目再进行删除！");
				return map;
			}
			ArchivesDto ardto = new ArchivesDto();
			ardto.setColtypeid(id);
			List<Map<String, Object>> archives = archivesService.finder(ardto);
			if(!CollectionUtils.isEmpty(archives)){
				map.put("success", false);
				map.put("message", "此栏目下有文档信息，请先删除文档再进行删除！");
				return map;
			}
			//查询要删除的目录下是否还有文档信息
			coltypeService.deleteByDto(dto);
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 查询方法
	 * */
	@RequestMapping(value = "/search")
	@ResponseBody
	public Map<String, Object> search(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", 0);
		ColumnDto dto = new ColumnDto();
		try {
			//当前登录人与当前管理站点信息
			User use = webUtil.getCurrUser();
			Map<String, Object> site = siteService.findByManagerId(use.getId());
			dto.setSiteid(site.get("id").toString());
			List<Map<String,Object>> rows = coltypeService.finder(dto);
			if(CollectionUtils.isEmpty(rows)){
				map.put("rows", "");
				return map;
			}
			for(Map<String, Object> row : rows){
				Object showStatus = row.get("showstatus");
				if(showStatus!=null){
					String strStatus = showStatus.toString();
					if("hidden".equals(strStatus))
						row.put("showstatus", "隐藏");
					else
						row.put("showstatus", "显示");
				}
				Date createTime = (Date)row.get("createTime");
				row.put("createTime", DateUtils.convertDate2String(createTime));
				row.put("id", row.get("number"));
				Object pnumber = row.get("pnumber");
				if(pnumber!=null)
					row.put("_parentId", pnumber);
			}
			map.put("rows", rows);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	@RequestMapping(value = "/zTreeAjax")
	@ResponseBody
	public List<Map<String, Object>> zTreeAjax(HttpServletRequest request){
		String checked = getParameter("checked");
		List<String> checkeds = NimsenUtil.convertStr2List(checked);
		List<Map<String, Object>> list = null;
		ColumnDto dto = new ColumnDto();
		try {
			addDtoSiteId(dto);
			list = coltypeService.finder(dto);
			for(Map<String,Object> map : list){
				Object number = map.get("number");
				String numberStr = number.toString();
				map.put("id", numberStr);
				Object pnumber = map.get("pnumber");
				if(pnumber!=null&&StringUtils.isNotBlank(pnumber.toString()))
					map.put("pId", pnumber.toString());
				else
					map.put("pId", "0");
				Object colname = map.get("colname");
				map.put("name", colname.toString());
				map.put("hrefurl", "");
				map.put("target", "_blank");
				//如果有选择的节点
				if(StringUtils.isBlank(checked))
					continue;
				if(checkeds.contains(numberStr))
					map.put("checked", "true");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return list;
	}
	private String addDtoSiteId(ColumnDto dto) throws Exception{
		//当前登录人与当前管理站点信息
		User use = webUtil.getCurrUser();
		Map<String, Object> site = siteService.findByManagerId(use.getId());
		String siteid = site.get("id").toString();
		dto.setSiteid(siteid);
		return siteid;
	}
}
